﻿using iText.IO.Font;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Utils;
using iText.Layout;
using iText.Layout.Element;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace txtToPDF
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        //txt转PDF
        private void BtnConvert_Click(object sender, EventArgs e)
        {
            try
            {
                this.btnConvert.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                foreach (object item in this.lstTxt.Items)
                {
                    //第一个参数是txt文件物理路径
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    string[] lines = System.IO.File.ReadAllLines(item.ToString(), Encoding.GetEncoding(0));
                    string outPdf = item.ToString()[..^4] + ".pdf";
                    FileInfo file = new(outPdf);
                    PdfWriter writer = new(file);
                    PdfDocument pdfDoc = new(writer);
                    Document doc = new(pdfDoc, iText.Kernel.Geom.PageSize.A4);


                    //创建我的基础字体
                    var engine = IronPython.Hosting.Python.CreateEngine();
                    dynamic py = engine.ExecuteFile("config.py");
                    string font_name = py.getFontName();

                    string fontName = @"C:\Windows\Fonts\msyhl.ttc,0";

                    //获取字体为空
                    if (string.IsNullOrWhiteSpace(font_name))
                    {
                        if (!File.Exists(@"C:\Windows\Fonts\msyhl.ttc"))
                        {
                            fontName = @"C:\Windows\Fonts\simsun.ttc,0";
                        }
                    }
                    else
                    {
                        if (!File.Exists(@"C:\Windows\Fonts\msyhl.ttc"))
                        {
                            fontName = @"C:\Windows\Fonts\simsun.ttc,0";
                        }
                        else
                        {
                            if (font_name.Equals("宋体"))
                            {
                                fontName = @"C:\Windows\Fonts\simsun.ttc,0";
                            }
                        }
                    }

                    PdfFont font = PdfFontFactory.CreateFont(fontName, PdfEncodings.IDENTITY_H);

                    Console.WriteLine(item.ToString() + "转换PDF文件正在开始!");
                    foreach (string line in lines)
                    {
                        doc.Add(new Paragraph(line).SetFont(font).SetFontSize(14));
                    }

                    Console.WriteLine(item.ToString() + "转换PDF文件完成!");
                    doc.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("异常信息:" + ex.Message);
            }
            finally
            {
                this.btnConvert.Enabled = true;
                this.Cursor = Cursors.Default;
            }

        }

        //浏览txt文件
        private void BtnBrowser_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfile = new()
            {
                Multiselect = true,
                Title = "请选择txt文件",
                //过滤文件类型
                Filter = "文本文件|*.txt"
            };
            if (DialogResult.OK == openfile.ShowDialog())
            {
                //将选择的文件的全路径赋值给文本框
                foreach (string filename in openfile.FileNames)
                {
                    lstTxt.Items.Add(filename);
                }
            }
        }

        //浏览PDF
        private void BtnBrowserPDF_Click(object sender, EventArgs e)
        {
            OpenFileDialog openfile = new()
            {
                Multiselect = true,
                Title = "请选择pdf文件",
                //过滤文件类型
                Filter = "PDF文件|*.pdf"
            };
            if (DialogResult.OK == openfile.ShowDialog())
            {
                //将选择的文件的全路径赋值给文本框
                foreach (string filename in openfile.FileNames)
                {
                    lstPDF.Items.Add(filename);
                }
            }
        }

        //合并PDF
        private void BtnMerge_Click(object sender, EventArgs e)
        {
            try
            {
                this.btnMerge.Enabled = false;
                this.Cursor = Cursors.WaitCursor;
                List<string> filelist = new();
                string outFileDirectory = "";
                foreach (object item in this.lstPDF.Items)
                {
                    FileInfo f = new(item.ToString());
                    if (string.IsNullOrWhiteSpace(outFileDirectory))
                    {
                        outFileDirectory = f.DirectoryName;
                        outFileDirectory = Path.Combine(outFileDirectory, DateTime.Now.ToLongDateString() + ".pdf");
                    }

                    filelist.Add(item.ToString());
                }

                if (filelist != null && filelist.Count > 0)
                {
                    Console.WriteLine("合并PDF文件正在开始!");
                    MergePDFFiles(filelist, outFileDirectory);
                    Console.WriteLine("合并PDF文件已经完成!");
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine("异常信息:" + ex.Message);
            }
            finally
            {
                this.btnMerge.Enabled = true;
                this.Cursor = Cursors.Default;
            }
        }

        private static void MergePDFFiles(List<string> fileList, string outMergeFile)
        {


            PdfWriter writer = new PdfWriter(outMergeFile);
            PdfDocument document = new PdfDocument(writer);
            PdfMerger merger = new(document);

            for (int i = 0; i < fileList.Count; i++)
            {
                PdfDocument pdf = new(new PdfReader(fileList[i]));
                merger.Merge(pdf, 1, pdf.GetNumberOfPages());
                pdf.Close();

                Console.WriteLine(fileList[i] + "合并PDF文件正在进行!");
            }

            merger.Close();
            document.Close();
        }

        //清空txt列表
        private void BtnClearTxt_Click(object sender, EventArgs e)
        {
            this.lstTxt.Items.Clear();
        }

        //清空PDF列表
        private void BtnClearPDF_Click(object sender, EventArgs e)
        {
            this.lstPDF.Items.Clear();
        }
    }
}
